package frobagroup.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Tinsley on 2016/11/22.
 */
@Component
public class JwtUtil {

    @Value("${jwt.secretkey}")
    private String SECRET_KEY;


    public String generateToken(String sub, String role) {
        return Jwts.builder().setSubject(role)
                .claim("userId", sub).setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
    }

    public String generateToken(String key, Object value, String sub) {
        Map<String, Object> map = new HashMap<>();
        map.put(key, value);
        if (StringUtils.isEmpty(sub)) {
            return Jwts.builder().setClaims(map).setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
        } else {
            return Jwts.builder().setSubject(sub).setClaims(map).setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
        }

    }

    public String generateToken(Map<String, Object> claims) {
        if (claims != null && claims.size() > 0) {
            return Jwts.builder().setClaims(claims).setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
        }else{
            return Jwts.builder().setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
        }

    }

    public Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY)
                .parseClaimsJws(token).getBody();
    }

    public static void setPrintWriter(int statusCode,
                                      HttpServletResponse response, String message) {
        PrintWriter writer = null;
        try {
            response.setStatus(statusCode);
            writer = response.getWriter();
            writer.println(message);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}


